package dao;

import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dto.CarrierDTO;
import dto.VehiculoDTO;
import entities.CarrierEntity;
import entities.ClienteEntity;
import entities.VehiculoEntity;

public class CarrierDAO {

	private static CarrierDAO instancia = null;
	private static SessionFactory sf = null;
	
	private CarrierDAO(){}
	
	public static CarrierDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new CarrierDAO();
		} 
		return instancia;
	}
	
	//TODO: HACER LOS METODOS QUE REALIZAN LAS CONSULTAS Y/O INSERTS
	/*public float totalPorCliente(dto.Cliente cliente)
	{
		SessionFactory sf =  HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		org.hibernate.Transaction t =  session.beginTransaction();
		Double resultado = (Double)session.createQuery("select sum(i.cantidad *  i.precio) as importe from Pedido p inner join p.items i where p.cliente.codigo = :codigoCliente").setInteger("codigoCliente", cliente.getCodigo()).uniqueResult();
		Float r = Float.valueOf(String.valueOf(resultado));
		t.commit();
		session = null;
		return r;
	}*/
	
	public void grabarCarrier(CarrierEntity carrier){
		CarrierEntity ca = new CarrierEntity();
		ca.setNombre(carrier.getNombre());;
		ca.setPrecioKM(carrier.getPrecioKM());
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(ca);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void actualizarCarrier(CarrierEntity carrier){
		CarrierEntity ca = new CarrierEntity();
		ca.setNombre(carrier.getNombre());;
		ca.setPrecioKM(carrier.getPrecioKM());
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(ca);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public CarrierEntity LoadCarrier(int id) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		CarrierEntity car = (CarrierEntity) session.get(CarrierEntity.class, id);
		session.flush();
		session.getTransaction().commit();
		session.close();
		return car;
	}
	
	public List<CarrierEntity> getCarriers() {
		Session session = sf.openSession();
		session.beginTransaction();
		List<CarrierEntity> carriersEntity = null;
		List<CarrierDTO> carriers = null;
		//TODO: HACER EL HQL CON EL WHERE CORRESPONDIENTE
		carriersEntity = session.createQuery("from CarrierEntity").list();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return carriersEntity;
	}
}
